// index.js
var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
var login = require('../../utils/login.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    autoplay: true,
    interval: 3000,
    duration: 1000,
    goodsDetail: {},
    swiperCurrent: 0,
    hasMoreSelect: false,
    selectSize: "",
    selectSizePrice: 0,
    shopNum: 0,
    hideShopPopup: true,
    buyNumber: 0,
    buyNumMin: 0,
    buyNumMax: 0,
    propertyChildIds: "",
    propertyChildNames: "",
    canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
    favorite: false,
    CurrentPid: 0,
    ReviewListLength: 0,
    animationData: "",
    showModalStatus: false,
    skuTitles: [],
    attrvalue: "",
    img: "",
    TotalCount: "",
    groupBuyInfor: {},
    timer: {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
      leftTime: 0
    },
    shouwTimer:true,
    showTimer: true
  },
  //事件处理函数
  swiperchange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this;
    console.log('onLoad');
    console.log(e)
    that.setData({ CurrentPid: e.id });
    that.getGroupBuyProductInfo();
  },
  intervalTimer:function(){
    var that = this;
    var timers = setInterval(function () {
      var groupBuyInfor = that.data.groupBuyInfor
      var EndTime = groupBuyInfor.EndTime
      var StartTime = groupBuyInfor.StartTime
      var timearr = EndTime.replace(" ", ":").replace(/\:/g, "-").split("-");//分割日期正则
      var year = timearr[0]
      var month = timearr[1]
      var day = timearr[2]
      var hour = timearr[3]
      var minute = timearr[4]
      var second = timearr[5]
      if (StartTime == EndTime || !that.data.shouwTimer || !that.data.showTimer) {
        clearInterval(timers)//清除计时
      } else{
        that.leftTimer(year, month, day, hour, minute, second)
      }
    }, 1000)
  },
  //时间计时
  leftTimer: function (year, month, day, hour, minute, second) {
    var that =this;
    var leftTime = (new Date(year, month - 1, day, hour, minute, second)) - (new Date()); //计算剩余的毫秒数 
    var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数 
    var hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10); //计算剩余的小时 
    var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);//计算剩余的分钟 
    var seconds = parseInt(leftTime / 1000 % 60, 10);//计算剩余的秒数 
    days = that.checkTime(days);
    hours = that.checkTime(hours);
    minutes = that.checkTime(minutes);
    seconds = that.checkTime(seconds);
    var timer = {}
    timer.days = days
    timer.hours = hours
    timer.minutes = minutes
    timer.seconds = seconds
    timer.leftTime = leftTime
    if (leftTime > 0) {
      that.setData({
        timer: timer
      })
    } else {
      that.setData({
        showTimer: false
      })
    }
  },
  checkTime: function (i) { //将0-9的数字前面加上0，例1变为01 
    if (i < 10) {
      i = "0" + i;
    }
    return i;
  },
  //分享
  onShareAppMessage: function () {
    var fromuid = app.globalData.userInfo.Uid;
    return {
      title: this.data.goodsDetail.ProductInfo.Name,
      path: '/pages/pintuan-details/index?id=' + this.data.CurrentPid,
      success: function (res) {
        // 转发
        wx.showModal({
          title: '提示',
          content: '转发成功',
          showCancel: false
        })
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  selectGoods: function (e) {
    console.log("点击商品评价")
    console.log(e)
    wx.navigateTo({
      url: '/pages/pingjia-list/index?pid=' + this.data.CurrentPid
    })
  },
  numJianTap: function () {
    if (this.data.buyNumber > this.data.buyNumMin) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  numJiaTap: function () {
    if (this.data.buyNumber < this.data.buyNumMax) {
      var currentNum = this.data.buyNumber;
      currentNum++;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  addShopCar: function (e) {
    console.log(e)
    if (e != 0) {
      var add = e.currentTarget.dataset.add
    }
    var that = this;
    if (this.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '暂时缺货哦~',
        showCancel: false
      })
      return;
    }

    wx.request({
      url: app.globalData.host + '/api/cart/AddProduct',
      data: {
        uid: app.globalData.userInfo.Uid,
        pid: that.data.CurrentPid,
        buyCount: that.data.buyNumber
      },
      success: function (res) {
        console.log(res);
        if (res.data.Code == 0) {
          that.setData({
            shopNum: res.data.Data
          });
          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 2000,
            success: function () {
              if (add != 1) {
                that.goShopCar();
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  goShopCar: function () {
    wx.navigateTo({
      url: "/pages/shop-cart/index"
    });
  },
  tokefu:function(){
    wx.switchTab({
      url: '/pages/kefu/index',
    })
  },
  tobuy: function () {
    if (this.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '暂时缺货哦~',
        showCancel: false
      })
      return;
    }
    this.addShopCar(0);
  },
  favorite: function (e) {
    console.log(e);
    var that = this;
    var pid = e.currentTarget.dataset.id;
    wx.request({
      url: app.globalData.host + '/api/user/ProductFavorite',
      data: {
        pid: pid,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        console.log(res);
        if (res.data.Code == 0) {
          var oldF = that.data.favorite;
          if (oldF) {
            wx.showModal({
              title: '取消收藏成功',
              content: '',
              showCancel: false
            })
          } else {
            wx.showModal({
              title: '收藏成功',
              content: '',
              showCancel: false
            })
          }
          that.setData({ favorite: !oldF })
        }

      }
    })
  },
  initPage: function () {
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    // 获取购物车数据
    wx.request({
      url: app.globalData.host + '/api/cart/index',
      data: {
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        console.log(res);
        if (res.data.Code == 0) {
          that.setData({ shopNum: res.data.Data.TotalCount })
        }

      }
    })

    wx.request({
      url: app.globalData.host + '/api/user/CheckProductFavorite',
      data: {
        pid: that.data.CurrentPid,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        var f = res.data.Data;
        that.setData({ favorite: f })
      }
    })
    wx.request({
      url: app.globalData.host + '/api/store/Product',
      data: {
        pid: that.data.CurrentPid
      },
      success: function (res) {
        console.log(res);
        var p = res.data.Data;
        if (!p.ProductInfo || p.ProductInfo.State != 0) {
          wx.showModal({
            title: '商品已下架',
            content: '',
            showCancel: false
          })
          return;
        }
        p.ProductInfo.countPrice = parseInt(p.ProductInfo.MarketPrice - p.ProductInfo.ShopPrice)//市场价和本店价价格差
        if (p.ProductInfo.ShowImg) {
          p.ProductInfo.ShowImg = app.globalData.image800_800host + p.ProductInfo.ShowImg;
        }
        for (var i = 0; i < p.ProductImageList.length; i++) {
          p.ProductImageList[i].ShowImg = app.globalData.image800_800host + p.ProductImageList[i].ShowImg;
        }
        if (p.ExtGiftList) {
          for (var i = 0; i < p.ExtGiftList.length; i++) {
            p.ExtGiftList[i].ShowImg = app.globalData.image190_190host + p.ExtGiftList[i].ShowImg;
          }
        }

        var selectSizeTemp = "";
        var pnames = "";
        if (p.CurrProductSkuList.length > 0) {
          for (var i = 0; i < p.CurrProductSkuList.length; i++) {
            pnames += p.CurrProductSkuList[i].AttrName + ":";
            var value = p.CurrProductSkuList[i].AttrValue;
            if (p.CurrProductSkuList[i].IsInput) {
              value = p.CurrProductSkuList[i].InputValue;
            }
            selectSizeTemp = selectSizeTemp + " " + value;
            pnames += value + " "
          }
          that.setData({
            hasMoreSelect: true,
            selectSize: that.data.selectSize + selectSizeTemp,
            selectSizePrice: p.ProductInfo.ShopPrice,
            propertyChildNames: pnames
          });
        }
        console.log("p")
        console.log(p)
        that.setData({
          goodsDetail: p,
          selectSizePrice: p.ProductInfo.ShopPrice,
          buyNumMax: p.StockNumber,
          buyNumber: (p.StockNumber > 0) ? 1 : 0
        });
        console.log("商品详情")
        WxParse.wxParse('article', 'html', p.ProductInfo.Description, that, 5);
        wx.hideLoading();
      }
    })
    that.pingjiaList(that.data.CurrentPid)
  },
  //获取拼团信息
  getGroupBuyProductInfo: function () {
    var that = this
    wx: wx.request({
      url: app.globalData.host + '/api/Store/GetGroupBuyProductInfo?storeId=' + app.globalData.storeId + '&pid=' + that.data.CurrentPid,
      success: function (res) {
        if (res.data.Code == 0) {
          var GroupBuyInfor = {}
          GroupBuyInfor.GroupBuyPrice = res.data.Data.GroupBuyPrice//团购价
          GroupBuyInfor.StartTime = res.data.Data.GroupBuy.StartTime//开始时间
          GroupBuyInfor.EndTime = res.data.Data.GroupBuy.EndTime//结束时间
          GroupBuyInfor.Status = res.data.Data.GroupBuy.Status// 0:开启，1：关闭
          GroupBuyInfor.LimitBuyerCount = res.data.Data.GroupBuy.LimitBuyerCount//拼团人数,
          that.setData({
            groupBuyInfor: GroupBuyInfor
          })
        }
      }
    })
  },
  //获取评价列表
  pingjiaList: function (pid) {
    var that = this;
    var postDatalist = {
      uid: app.globalData.userInfo.Uid,
      page: 1
    };
    wx.request({
      url: app.globalData.host + '/api/store/productreviewlist?pid=' + pid + '&page=1',
      success: (res) => {
        console.log("评价列表");
        console.log(res);
        var ReviewListTwo = [];
        that.setData({
          ReviewListLength: res.data.Data.ProductReviewList.length,
          TotalCount: res.data.Data.PageModel.TotalCount
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (app.globalData.userInfo) {
      console.log("用户信息存在")
      that.initPage();
      if (that.data.shouwTimer){
        that.intervalTimer();
      }
    } else {
      console.log("用户信息不存在,延时加载")
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      shouwTimer: false
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
})